<!-- 考试记录 -->
<template>
  <div class="app-container">
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="班级">
          <el-input
            v-model="queryParams.className"
            placeholder="班级"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 考试记录列表 -->
    <el-table v-loading="loading" :data="recordList" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column
        prop="paperName"
        label="试卷名称"
        show-overflow-tooltip
      />
      <!-- <el-table-column prop="className" label="班级" width="120" /> -->
      <el-table-column prop="score" label="得分" width="80" />
      <el-table-column label="用时(分钟)" width="100">
        <template #default="{ row }">
          {{ Math.round(row.duration / 60) }}
        </template>
      </el-table-column>
      <el-table-column prop="paperTime" label="考试时间" width="180" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleViewDetails(row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 成绩统计 -->
    <!-- <el-row :gutter="20" class="statistics-row" v-if="isTeacher">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>班级成绩分布</span>
            </div>
          </template>
          <div class="chart-container" ref="chartRef"></div>
        </el-card>
      </el-col>
    </el-row> -->

    <!-- 查看详情对话框 -->
    <el-dialog
      title="考试详情"
      v-model="detailsDialogVisible"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="试卷名称">
          {{ currentRecord.paperName }}
        </el-descriptions-item>
        <el-descriptions-item label="得分">
          {{ currentRecord.score }}
        </el-descriptions-item>
        <el-descriptions-item label="用时">
          {{ Math.round(currentRecord.duration / 60) }}分钟
        </el-descriptions-item>
        <!-- <el-descriptions-item label="考试时间">
          {{ currentRecord.createdTime }}
        </el-descriptions-item> -->
        <el-descriptions-item label="试卷时长">
          {{ currentRecord.paperTime }}分钟
        </el-descriptions-item>
      </el-descriptions>

      <el-table :data="questionList" style="width: 100%; margin-top: 20px">
        <el-table-column prop="questionType" label="类型" width="100">
          <template #default="{ row }">
            <el-tag
              :type="row.questionType === 'single' ? 'primary' : 'success'"
            >
              {{ row.questionType === "single" ? "单选题" : "多选题" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="questionText"
          label="题目内容"
          show-overflow-tooltip
        />
        <el-table-column prop="answer" label="你的答案" width="100" />
        <el-table-column prop="correctAnswer" label="正确答案" width="100" />
        <el-table-column prop="score" label="得分" width="80" />
        <el-table-column prop="isCorrect" label="是否正确" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isCorrect ? 'success' : 'danger'">
              {{ row.isCorrect ? "正确" : "错误" }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage } from "element-plus";
import * as echarts from "echarts";
import {
  getRecords,
  getRecordDetails,
  getClassScoreStatistics,
} from "@/api/exam";

const isTeacher = computed(
  () => localStorage.getItem("userRole") === "teacher"
);

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  className: "",
});

// 考试记录列表数据
const loading = ref(false);
const recordList = ref([]);
const total = ref(0);

// 获取考试记录列表
const getRecordList = async () => {
  loading.value = true;
  try {
    const { records, total: totalCount } = await getRecords(queryParams);
    recordList.value = records;
    total.value = totalCount;
  } catch (error) {
    console.error("获取考试记录失败：", error);
  } finally {
    loading.value = false;
  }
};

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1;
  getRecordList();
};

// 重置按钮点击
const resetQuery = () => {
  queryParams.className = "";
  handleQuery();
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getRecordList();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getRecordList();
};

// 查看详情相关
const detailsDialogVisible = ref(false);
const currentRecord = ref({});
const questionList = ref([]);

// 查看详情按钮点击
const handleViewDetails = async (row) => {
  try {
    currentRecord.value = row;
    const details = await getRecordDetails(row.id);
    questionList.value = details;
    detailsDialogVisible.value = true;
  } catch (error) {
    console.error("获取考试详情失败：", error);
  }
};

// 图表相关
const chartRef = ref(null);
let chart = null;

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;
  chart = echarts.init(chartRef.value);
};

// 更新图表数据
const updateChart = async () => {
  if (!chart || !isTeacher.value) return;
  try {
    const data = await getClassScoreStatistics();
    chart.setOption({
      title: {
        text: "班级成绩分布",
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      xAxis: {
        type: "category",
        data: ["0-59", "60-69", "70-79", "80-89", "90-100"],
      },
      yAxis: {
        type: "value",
        name: "人数",
      },
      series: [
        {
          name: "学生人数",
          type: "bar",
          data: data.studentCounts,
          itemStyle: {
            color: "#409EFF",
          },
        },
      ],
    });
  } catch (error) {
    console.error("获取成绩统计数据失败：", error);
  }
};

onMounted(() => {
  getRecordList();
  if (isTeacher.value) {
    initChart();
    updateChart();
  }
});
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-form {
  flex: 1;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.statistics-row {
  margin-top: 20px;
}

.chart-card {
  height: 400px;
}

.chart-container {
  height: 100%;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
